package cn.tom.tompicturebackend.aop;

import cn.tom.tompicturebackend.annotation.AuthCheck;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;
import cn.tom.tompicturebackend.model.entity.User;
import cn.tom.tompicturebackend.model.enums.UserRoleEnum;
import cn.tom.tompicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint joinPoint,AuthCheck authCheck)throws Throwable{
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttribute = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttribute).getRequest();
        //当前登录用户
        User loinUser = userService.getLoinUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限，放行
        if(mustRoleEnum == null){
            return joinPoint.proceed();
        }
        //以下为:必须有该权限才通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loinUser.getUserRole());

        //没有权限，拒接
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NOT_AUTHORIZED_ERROR);
        }
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NOT_AUTHORIZED_ERROR);
        }
        //通过权限校验,放行
        return joinPoint.proceed();

    }
}
